import { Component, OnInit } from '@angular/core';
import { RouterModule } from '@angular/router';
import { CommonModule } from '@angular/common';

import { FormBuilder, FormGroup, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { AppService } from '../../services/app.service';
import { Router } from '@angular/router';
import { delay, first } from 'rxjs';
import { SidebarComponent } from '../../modules/sidebar/sidebar.component';
import { trigger } from '@angular/animations';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-edit-user',
  standalone: true,
  imports: [SidebarComponent, RouterModule,
    FormsModule,
    ReactiveFormsModule,
    CommonModule,
    HttpClientModule,],
  templateUrl: './edit-user.component.html',
  styleUrl: './edit-user.component.scss'
})
export class EditUserComponent implements OnInit {
  public updateUserForm: FormGroup;
  public userList: any = [];
  public userListSubscribe: any;
  public user_id: any;
  constructor(private fb: FormBuilder, private appService: AppService, private route: Router, private active: ActivatedRoute) {
    this.updateUserForm = this.fb.group({
      username: ['', Validators.required],
      password: ['', Validators.required],
      phone: ['', Validators.required],
      privileges: [null, Validators.required],
    });
  }
  async ngOnInit() {
    this.user_id = this.active.snapshot.paramMap.get('user_id');
    this.userListSubscribe = await this.appService.loadUserByID(this.user_id).subscribe(res => {
      console.log('res', res);
      this.userList = res;
    });
  }
  async updateUserByID(updateUserForm: any) {
    if (updateUserForm.valid) {
      this.user_id = this.active.snapshot.paramMap.get('user_id');
      this.appService.updateUserByID(
        updateUserForm.value.username,
        updateUserForm.value.password,
        updateUserForm.value.phone,
        updateUserForm.value.privileges,
        this.user_id
      ).pipe(first())
        .subscribe(data => {
          console.log(data);
          if (data.message == 'Update User Success') {
            alert('แก้ไข User สำเร็จ');
            this.route.navigate(['/admin-page']);
          }
          if (data.message == 'Update User Falied') {
            alert('แก้ไข User ไม่สำเร็จ');
          }
        }, error => {
          alert("แก้ไข User ไม่สำเร็จ");
        })
    }
    if (!updateUserForm.valid) {
      alert("กรุณากรอกให้ครบ");
    }
  }

  async deleteUser(){
    this.user_id = this.active.snapshot.paramMap.get('user_id');
    this.appService.deleteUserByID(this.user_id).pipe(first()).subscribe(data => {
      if (data.message == 'Delete User Successful') {
        alert('ลบ User สำเร็จ');
        this.route.navigate(['/admin-page']);
      }
      if (data.message == 'Delete User Falied') {
        alert('ลบ User ไม่สำเร็จ');
      }
    });
  }

}